//
//  GSSearchViewNavigationView.m
//  GameSky
//
//  Created by lanou on 16/1/14.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSSearchViewNavigationView.h"

@interface GSSearchViewNavigationView () <UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
/**
 * 数据库
 */
@property (nonatomic, strong) FMDatabase *db;
// 数据库
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
@implementation GSSearchViewNavigationView
// 重写初始化方法
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        // 夜间模式
        self.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
        
// 获取数据
        [self getDataByDB];
        
        NSArray *titleArray = @[@"大家都在搜",@"搜索历史"];
        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;
        self.nagavigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 42)];
        _nagavigationView.backgroundColor = [UIColor orangeColor];
        [self addSubview:_nagavigationView];
        for (int i = 0; i < 2; i++) {
// button
            UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
            button.tag = 100 + i;
            if (i == 0) {
                button.selected = YES;
            }
            // 添加方法
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [button setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
            [button setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
            [button setTitle:titleArray[i] forState:(UIControlStateNormal)];
            button.frame = CGRectMake(0 + (i * _nagavigationView.width / 2), 0, _nagavigationView.width / 2, _nagavigationView.height);
            [_nagavigationView addSubview:button];
        }
// scrollView
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _nagavigationView.bottom, kScreenWidth, height - _nagavigationView.bottom)];
        _scrollView.pagingEnabled = YES;
        _scrollView.contentSize = CGSizeMake(kScreenWidth * 2, _scrollView.height);
        _scrollView.bounces = NO;
        _scrollView.delegate = self;
        _scrollView.alwaysBounceVertical = NO;
        _scrollView.alwaysBounceHorizontal = YES;
// 在self.scrollView 上 添加 scrollView
//        self.allSearchScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, _scrollView.height - 216)];
//        _allSearchScrollView.bounces = NO;
//        _allSearchScrollView.delegate = self;
//        [_scrollView addSubview:_allSearchScrollView];

        self.searchHistoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, _scrollView.height - 216 - 40) style:(UITableViewStylePlain)];
        _searchHistoryTableView.delegate = self;
        _searchHistoryTableView.dataSource = self;
        // 清楚所有 搜索记录按钮
        UIButton *clearButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        clearButton.frame = CGRectMake(0, 0, kScreenWidth, 30);
        [clearButton setTitle:@"清除搜索历史" forState:(UIControlStateNormal)];
        clearButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [clearButton setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        // 添加方法
        [clearButton addTarget:self action:@selector(clearButtonAction:)
              forControlEvents:(UIControlEventTouchUpInside)];
        _searchHistoryTableView.tableFooterView = clearButton;
        
        [_scrollView addSubview:self.searchHistoryTableView];
        
        [self addSubview:_scrollView];
    }
    return self;
}
#pragma mark-------------从数据库提取所需数据-----------------
- (void)getDataByDB{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    // 拼接路径
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    // 取出 存储的 数据 展示
    FMResultSet *resultSet = [_db executeQuery:@"select * from SearchHistoryList"];
    while ([resultSet next]) {
        NSString *history = [resultSet stringForColumn:@"history"];
        [arr addObject:history];
    }
// 将  从数据库提取到的数组  ,倒序
   NSArray *array = [[arr reverseObjectEnumerator] allObjects];
    // 给  数据源数据   赋值
    self.dataArray = [NSMutableArray arrayWithArray:array];
    
}
#pragma mark---------------标签button点击方法---------------
- (void)buttonAction:(UIButton *)button{
    for (UIButton *oneButton in _nagavigationView.subviews) {
        if (oneButton.tag == button.tag) {
            oneButton.selected = YES;
            [_scrollView setContentOffset:CGPointMake((oneButton.tag - 100) * kScreenWidth, 0) animated:YES];
            
        }else{
            oneButton.selected = NO;
        }
    }
}
#pragma mark---------------清楚搜索历史按钮----------------
- (void)clearButtonAction:(UIButton *)button{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    // 拼接路径
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    if (![_db executeUpdate:@"delete from SearchHistoryList"]) {
        NSLog(@"删除所有数据失败");
    }
// 刷新界面
    [self getDataByDB];
    [_searchHistoryTableView reloadData];
    
}
#pragma mark---------------tableView协议-----------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    NSString *str = _dataArray[indexPath.row];
    cell.textLabel.text = str;
    return cell;
}
// cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // block调用
    NSString *str = _dataArray[indexPath.row];
    self.cellSelected(str);
}
#pragma mark---------------scrollView协议-------------------
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // 判断 滑动的视图
    if ([scrollView isEqual:_scrollView]) {
        CGFloat x = scrollView.contentOffset.x /  kScreenWidth;
        NSInteger num = (NSInteger)100 + x;
        // 取出对应的button, 重新 执行一边,button点击方法
        UIButton *button = (UIButton *)[_nagavigationView viewWithTag:num];
        [self buttonAction:button];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
